﻿using ConfExpert.Forms.Base;
using ConfExpert.Forms.SatinAlma.YeniYapi;
using ConfExpert.Properties;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.BandedGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;
using System;
using System.Drawing;

namespace ConfExpert.Forms.SatinAlma
{
    public partial class AlisFaturasi : XForm
    {
        int AlisFaturasiId = 0;
        public AlisFaturasi()
        {
            InitializeComponent();
        }

        public AlisFaturasi(int AlisFaturasiId)
            : this()
        {
            this.AlisFaturasiId = AlisFaturasiId;
            this.Text += " - " + AlisFaturasiId.ToString();
        }

        Color[] colors;
        private void AlisFaturasi_Load(object sender, EventArgs e)
        {
            gridView1.Init("GetAlisFaturasi1", AlisFaturasiId);
            gridView1.AddDetailGrid(gvMasraf, "AlisFaturasiId");

            gridView1.AddColumn("Masraf1", typeof(decimal), "SUM(Child({FK}).Tutar)");
            gridView1.AddColumn("Toplam1", typeof(decimal), "ISNULL(Masraf1,0)+ISNULL(LineTotals,0)");

            //            GridManager gm = GridManager.GetManager(gridView1);
            //gm.GridMenu.AddMenu("Aç", Ac);

            gvMasraf.SetViewCaption("Masraflar");
            gvMasraf.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;
            //gvMarka.OptionsView.ShowAutoFilterRow = false;
            gvMasraf.FormatAsNumber(2, "Tutar");
            gvMasraf.AddSummary("Tutar");
            gvMasraf.SetCaptions("AlisFaturasiMasrafId:#");
            gvMasraf.MakeColumnInvisible("AlisFaturasiId");
            gvMasraf.BestFitColumns();

            colors = new Color[]{
            Color.WhiteSmoke,
            Color.Khaki,
            Color.FromArgb(238, 243, 213),

            Color.Khaki,
            Color.FromArgb(220, 232, 162)
            };

            PrepareBands(gridView1);
            gridView1.YanYanaGetir("SipNo:AlisFaturasiId");

            gridView1.Columns["Masraf1"].OwnerBand =
            gridView1.Columns["Toplam1"].OwnerBand =
            gridView1.Columns["FaturaToplami"].OwnerBand = gridView1.Bands["gb1"];
            gridView1.YanYanaGetirSoluna("NakliyeciId", "Masraf1", "Toplam1", "FaturaToplami", "CurrencyId");

            //gridView1.DataTable().Columns["InvoiceTutar"].Expression = "(((((((((isnull([LineTotals],(0))+isnull([Deposit],(0)))+isnull([Bonus2Kalite],(0)))+isnull([Indirim],(0)))+isnull([_2KaliteIndirim],(0)))+isnull([NavlunBedeli],(0)))+isnull([KalipBedeli],(0)))+isnull([NumuneFarki],(0)))+isnull([Diger],(0)))+isnull([Surcharge],(0)))";
            gridView1.SetCaptions("SipNo:PO Nr.");

            RepositoryItemComboBox riOdemesi = new RepositoryItemComboBox();
            riOdemesi.Items.AddRange(new object[] { "BEDELLİ", "BEDELSİZ" });
            riOdemesi.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            gridView1.Columns["Odemesi"].ColumnEdit = riOdemesi;

            RepositoryItemComboBox riBirimi = new RepositoryItemComboBox();
            riBirimi.Items.AddRange(new object[] { "MT", "ADET" });
            riBirimi.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            gridView1.Columns["Birim2"].ColumnEdit = riBirimi;

            bbiKaydet.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
            bbiKaydet.ItemClick += bbiKaydet_ItemClick;
            gridView1.AddAutoIncrementalPK("AlisFaturasiId");
            //gridView1.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;
            gridView1.MakeColumnsReadOnly("AlisFaturasiId", "Ay", "Sezon", "Musteri", "SipNo", "LineTotals", "Masraf1", "Toplam1", "Miktar");

            gridView1.FormatAsDate("InvoiceTarihi");
            gridView1.FormatAsNumber(1, "Miktar");
            gridView1.FormatAsNumber(2, "LineTotals", "Masraf1", "Toplam1", "FaturaToplami");
            gridView1.AddSummary("LineTotals", "Masraf1", "FaturaToplami", "Miktar");

            //RestoreLayout();
            //bbiSaveLayout.ItemClick += bbiSaveLayout_ItemClick;

            bbiKaydet.Enabled = ytk(159);

            gridView1.RowCellStyle += gridView1_RowCellStyle;
            beiView.EditValueChanged += AlisFaturasi_SelectedIndexChanged;
            beiView.EditValue = ytk(160) ? "KD" : (ytk(161) ? "İTD" : "Hepsi");
            //((RepositoryItemComboBox)beiView.Edit).SelectedIndexChanged += AlisFaturasi_SelectedIndexChanged;

            gridView1.BestFitColumns();

            splitContainerControl1.SizeChanged += MySizeChanged2;
            ExpandCollapse(splitContainerControl1, AcKapa.Collapse);

            //if (AlisFaturasiId > 0)
            //{
            //    gridView1.FocusedRowHandle = gridView1.LocateByDisplayText(0, gridView1.Columns["AlisFaturasiId"], AlisFaturasiId.ToString());
            //    gridView1.MakeRowVisible(gridView1.FocusedRowHandle, true);
            //}

            gridView1.RowStyle += gridView1_RowStyle;
            bbiGuncelle.ItemClick += bbiGuncelle_ItemClick;

            if (isKD || isAdmin)
            {
                GridManager gm = GridManager.GetManager(gridView1);
                gm.GridMenu.AddMenu("Faturasını Düzenle", FaturayiDuzenle, Resources.Editor_Edit);
            }
        }

        private void FaturayiDuzenle(object sender, EventArgs e)
        {
            int AlisFaturasiId = gridView1.GetFocusedRowCellValue("AlisFaturasiId").ToInt();
            if (AlisFaturasiId > 0)
                using (YeniFatura yf = new YeniFatura(1, AlisFaturasiId))
                    yf.ShowDialog();
        }

        void bbiGuncelle_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView1.RefreshDataSource("GetAlisFaturasi1", AlisFaturasiId);
            gridView1.BestFitColumns();
        }

        void gridView1_RowStyle(object sender, RowStyleEventArgs e)
        {
            //siyah olanlar bir yüklemeye bağlı olan (yüklemesi olan) faturalar.. Renkli (açık yeşil) olanlar ise yüklemesi olmayan fatura girişleri (aksesuar faturaları gibi..)
            if (e.RowHandle > -1)
            {
                e.Appearance.ForeColor = Color.OliveDrab;

                if ((sender as GridView).GetRowCellValue(e.RowHandle, "Ek") != null)
                    if ((sender as GridView).GetRowCellValue(e.RowHandle, "Ek") != DBNull.Value)
                        if ((sender as GridView).GetRowCellValue(e.RowHandle, "Ek").ToInt() > 0)
                            e.Appearance.ForeColor = Color.Black;
            }
        }

        public void MySizeChanged2(object sender, EventArgs e)
        {
            SplitContainerControl scc = sender as SplitContainerControl;
            scc.SplitterPosition = (scc.Horizontal ? scc.Width : scc.Height) * 2 / 3;
        }

        void AlisFaturasi_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (beiView.EditValue.ToString())
            {
                case "KD":
                    gridView1.Bands["gb1"].Visible = true;
                    gridView1.Bands["gb2"].Visible = false;
                    break;
                case "İTD":
                    gridView1.Bands["gb1"].Visible = false;
                    gridView1.Bands["gb2"].Visible = true;
                    break;
                case "Hepsi":
                    gridView1.Bands["gb1"].Visible =
                    gridView1.Bands["gb2"].Visible = true;
                    break;
            }
        }

        //void bbiSaveLayout_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        //{
        //    gridControl1.MainView.SaveLayoutToXml(FileToSave/*, OptionsLayoutBase.FullLayout*/);
        //}

        //public string FileToSave
        //{
        //    get
        //    {
        //        return Session.TempDirectory + "\\AF_LAYOUT1.xml";    //_" + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".xml";
        //    }
        //}

        //void RestoreLayout()
        //{
        //    string layout = FileManager.ReadText(FileToSave);
        //    if (layout.Trim() == string.Empty)
        //        return;

        //    if (layout.Substring(0, 1) == "?")
        //        layout = layout.Substring(1);

        //    try
        //    {
        //        gridControl1.ForceInitialize();
        //        gridControl1.MainView.RestoreLayoutFromXml(FileToSave);
        //    }
        //    catch
        //    {
        //        File.Delete(FileToSave);
        //    }
        //}


        void gridView1_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            GridView view = sender as BandedGridView;

            //if (e.RowHandle == view.FocusedRowHandle)
            //    e.Appearance.BackColor = Color.YellowGreen; // SystemColors.ControlDark;
            //else
            //    e.Appearance.Combine((e.RowHandle & 1) != 0 ? view.Appearance.EvenRow : view.Appearance.OddRow);

            if (e.RowHandle > -1)
                try
                {
                    if (e.Column.FieldName == "BrandId" ||
                        e.Column.FieldName == "FaturaNo")
                    {
                        e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
                    }
                }
                catch
                {
                }

        }

        void bbiKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView1.EndEditing();
            gvMasraf.EndEditing();
            int A = intParse(gridView1.GetFocusedRowCellValue("AlisFaturasiId"));

            gridView1.Update("", "AlisFaturasi");
            gvMasraf.Update("", "AlisFaturasiMasraf");  //TODO: bu grid, neden saklanamıyor?
            ExecuteNonQuery("UpdAlisFaturasi_stf");

            gridView1.RefreshDataSource(true, "GetAlisFaturasi1", AlisFaturasiId);    //TODO: oluşan id'leri, computed column değerlerini nasıl alabiliriz bütün tabloyu çekmeden??
            gridView1.FocusedRowHandle = gridView1.LocateByValue(0, gridView1.Columns["AlisFaturasiId"], A);
            gridView1.MakeRowVisible(gridView1.FocusedRowHandle);
        }

        void PrepareBands(BandedGridView gv)
        {
            int cnt = 0;
            gv.Images = bandImages;
            string[] parts = "REFERANS;KUMAŞ BÖLÜMÜ;İTHALAT BÖLÜMÜ".Split(';');
            string[] starts = "AlisFaturasiId;LineTotals;KarbelReferans;".Split(';');
            for (int i = 0; i < parts.Length; i++)
            {
                GridBand gb = new DevExpress.XtraGrid.Views.BandedGrid.GridBand();
                gb.Caption = "<b>" + parts[i] + "</b>";
                gb.ImageIndex = i;
                gb.Name = "gb" + gb.ImageIndex.ToString();
                //TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                gb.OptionsBand.AllowHotTrack = true;
                gv.Bands.Add(gb);

                for (int i2 = cnt; i2 < gv.Columns.Count; i2++)
                {
                    if (gv.Columns[cnt].FieldName == starts[i + 1] && cnt > 0)
                        break;

                    gv.Bands[i].Columns.Add(gv.Columns[cnt]);

                    cnt++;
                }
            }

            gv.OptionsView.AllowHtmlDrawHeaders = true;
        }



    }
}
